package com.bestescortbedsystem.controller.qianduan;

import com.bestescortbedsystem.dao.SesUserDao;
import com.bestescortbedsystem.entity.Head;
import com.bestescortbedsystem.entity.SesUser;
import com.bestescortbedsystem.entity.SesUserExample;
import com.bestescortbedsystem.service.LoginService;
import com.bestescortbedsystem.service.UserService;
import com.bestescortbedsystem.util.FileUtil;
import com.bestescortbedsystem.util.FindDate;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


/**
 * ClassName: LoginController
 * Package: com.bestescortbedsystem.controller
 *
 * @author: guanzepeng
 * @Date: 2021/2/18 17:27 星期四
 * @Description: 登录判定的controller
 */
@Controller
@RequestMapping("/login")
@Slf4j
@Api(tags = "用户的controller")
public class LoginController {

	@Resource
	private LoginService loginService;

	@Resource
	private UserService userService;

	@Resource
	private SesUserDao sesUserDao;

	/**
	 * 登出功能
	 * @param i 传入1为管理员退出,0为普通用户退出
	 * @return 返回重定向
	 */
	@RequestMapping (value = "/logout", method = RequestMethod.GET)
	public String logOut() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
			return "redirect:/user/Login.html";
	}

	/**
	 * 进行登录验证
	 * @param username 输入手机号
	 * @param password 输入密码
	 * @return 返回
	 */
	@RequestMapping (value = "/getlogin",method = RequestMethod.POST)
	@ApiOperation(value = "进行登录验证的方法",response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username",value = "用户手机号",required = true,dataTypeClass = Long.class),
			@ApiImplicitParam(name = "password",value = "用户密码",required = true,dataTypeClass = String.class)
	})
	public String getlogin(HttpSession session, String username, String password){
		//获取认证主体对象
		Subject subject = SecurityUtils.getSubject();
		try{
			subject.login(new UsernamePasswordToken(username,password));
			SesUserExample sesUserExample = new SesUserExample();
			sesUserExample.createCriteria().andUserphoneEqualTo(Long.valueOf(username));

			List<SesUser> sesUsers = sesUserDao.selectByExample(sesUserExample);
			String id = String.valueOf(sesUsers.get(0).getUserid());
			String usernames = sesUsers.get(0).getUsername();

			SesUser sesUser = new SesUser();
			sesUser.setUserlogincount(sesUsers.get(0).getUserlogincount() + 1);
			sesUser.setUserlogintime(FindDate.getDate());
			sesUser.setUserlastlogintime(FindDate.getDate());
			SesUserExample sesUserExample1 = new SesUserExample();
			sesUserExample1.createCriteria().andUseridEqualTo(sesUsers.get(0).getUserid());
			sesUserDao.updateByExampleSelective(sesUser, sesUserExample1);

			//存储用户ID到session中
			session.setAttribute("userId2",id);
			session.setAttribute("username2",usernames);
				return "redirect:/webapp/UserMain.html";
		}catch (UnknownAccountException e){
			e.printStackTrace();
			log.info("用户名错误!");
		}catch (IncorrectCredentialsException e){
			e.printStackTrace();
			log.info("密码错误!");
		}
		return "redirect:/user/Login.html";
	}

	/**
	 * 进行管理员登录验证
	 * @param username 输入手机号
	 * @param password 输入密码
	 * @return 返回
	 */
	@RequestMapping (value = "/getadminlogin",method = RequestMethod.POST)
	@ApiOperation(value = "进行管理员登录验证的方法",response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username",value = "用户手机号",required = true,dataTypeClass = Long.class),
			@ApiImplicitParam(name = "password",value = "用户密码",required = true,dataTypeClass = String.class)
	})
	public String getAdminlogin(HttpSession session, String username, String password){
		//获取认证主体对象
		Subject subject = SecurityUtils.getSubject();
		try{
			subject.login(new UsernamePasswordToken(username,password));
			SesUserExample sesUserExample = new SesUserExample();
			sesUserExample.createCriteria().andUserphoneEqualTo(Long.valueOf(username));

			List<SesUser> sesUsers = sesUserDao.selectByExample(sesUserExample);
			String id = String.valueOf(sesUsers.get(0).getUserid());
			String usernames = sesUsers.get(0).getUsername();

			SesUser sesUser = new SesUser();
			sesUser.setUserlogincount(sesUsers.get(0).getUserlogincount() + 1);
			sesUser.setUserlogintime(FindDate.getDate());
			sesUser.setUserlastlogintime(FindDate.getDate());
			SesUserExample sesUserExample1 = new SesUserExample();
			sesUserExample1.createCriteria().andUseridEqualTo(sesUsers.get(0).getUserid());
			sesUserDao.updateByExampleSelective(sesUser, sesUserExample1);

			//存储用户ID到session中
			session.setAttribute("userId",id);
			session.setAttribute("username",usernames);
			return "redirect:/webapp/index.html";
		}catch (UnknownAccountException e){
			e.printStackTrace();
			log.info("用户名错误!");
		}catch (IncorrectCredentialsException e){
			e.printStackTrace();
			log.info("密码错误!");
		}
		return "redirect:/adminUser/Login.html";
	}

	/**
	 * 进行新用户注册
	 * @param sesUser 传入新用户注册数据
	 * @return 返回Boolean
	 */
	@RequestMapping(value = "/insertuser",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "进行新用户注册的方法,根据注册是否成功返回Boolean", response = Boolean.class)
	public Boolean insertUser(SesUser sesUser){
		Boolean b = loginService.insertUser(sesUser);
		return b;
	}

	/**
	 * 处理上传图片
	 * @param file
	 * @param model
	 * @return
	 */
	@RequestMapping("/doUpload")
	@ApiOperation(value = "处理用户头像上传的接口")
	public String uploadImg(
			HttpSession session,
			// 定义一个 MultipartFile 类型的参数 file
			@RequestParam("pclogo") MultipartFile file, Model model) throws InterruptedException {
		log.info("--------------------------------------进入了uploadImg方法----------------------------------------");
		// 如果图片为空,返回false
		if ((file.getOriginalFilename().isEmpty())) {
			log.info("图片为空");
		} else {
			Head head = new Head();
			// 获取图片的名字
			String fileName = file.getOriginalFilename();
			//添加UUID
			String uuid = UUID.randomUUID().toString();
			fileName = "/" + uuid + fileName;
			// 图片存放的文件夹地址
			String filePath = null;
			File directory = new File("src/main/resources/templates/img");
			try {
				filePath = directory.getCanonicalPath();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 文件夹地址 + 名字 = 图片的路径
			String fileAddress = "/img" + fileName;
			log.info("图片的路径为:" + fileAddress);
			try {
				// 图片上传的工具类
				// 参数一：图片的编码格式的字节数组
				// 参数二：图片存放的文件夹地址
				// 参数三：图片的名字
				log.info(filePath);
				log.info(fileName);
				FileUtil.uploadFile(file.getBytes(), filePath, fileName);
					// 把图片路径写入数据库
					head.setHeadAddress(fileAddress);
				String userId = (String) session.getAttribute("userId2");
					head.setId(Integer.valueOf(userId));
				boolean	b = userService.insertPhoto(head);
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		Thread.sleep(1000);
		return "redirect:/user/UserMoney.html";
	}
}

